<?php
class PayPal {
	private $token;
	private $API_UserName;
	private $API_Password;
	private $API_Signature;
	private $version		= '82.0';
	private $PAYPAL_URL		= 'https://www.paypal.com/cgi-bin/webscr&cmd=_express-checkout&useraction=commit&token=';
	private $API_ENDPOINT	= 'https://api-3t.paypal.com/nvp';
	// sandbox
	// private $PAYPAL_URL		= 'https://www.sandbox.paypal.com/cgi-bin/webscr&cmd=_express-checkout&useraction=commit&token=';
	// private $API_ENDPOINT	= 'https://api-3t.sandbox.paypal.com/nvp';

	//获取token的函数,amount(总金额),currency(usd),payType(sale),DESC(描述INVNUM
	public function SetExpressCheckout($params=array()) {
		$this->API_UserName		= $params['API_UserName'];
		$this->API_Password		= $params['API_Password'];
		$this->API_Signature	= $params['API_Signature'];

		$payAmount	= $params['amount'];//how much?
		$desc		= $params['DESC'];//describe
		$INVNUM		= $params['INVNUM'];//订单号
		$RETURNURL	= $params['RETURNURL'];//成功返回地址
		$CANCELURL	= $params['CANCELURL'];//失败返回地址
		$BRANDNAME	= $params['BRANDNAME'];//收款方名称
		$currency	= isset($params['currency'])?$params['currency']:'USD';//USD?RMD
		$payType	= isset($params['payType'])?$params['payType']:'sale';//sale?buy
		$EMAIL		= isset($params['EMAIL'])?$params['EMAIL']:'';//默认付款人paypal账号
		$nvpstr		= "&AMT=$payAmount&PAYMENTACTION=$payType&RETURNURL=$RETURNURL&CANCELURL=$CANCELURL&CURRENCYCODE=".$currency."&DESC=$desc&INVNUM=$INVNUM&EMAIL=$EMAIL&BRANDNAME=$BRANDNAME";
		$resArray	= self::makeCall("SetExpressCheckout", $nvpstr);
		$log = fopen('paypal.txt', 'a+');
		fwrite($log, "【SetExpressCheckout\t".$INVNUM."】\t".date('Y-m-d H:i:s')."\n".json_encode($resArray)."\n\n");
		fclose($log);
		if(!$resArray) {
			return false;
		}
		if(array_key_exists('ACK', $resArray) AND strtoupper($resArray['ACK']) == 'SUCCESS') {
			$this->token = urldecode($resArray["TOKEN"]);
			return $resArray['TOKEN'];
		} else {
			return false;
		}
	}

	public function jump(){
		header('Location:'.$this->PAYPAL_URL.$this->token);
	}

	public function GetExpressCheckoutDetails($params) {
		$this->API_UserName		= $params['API_UserName'];
		$this->API_Password		= $params['API_Password'];
		$this->API_Signature	= $params['API_Signature'];

		$token = urlencode($params['token']);
		$nvpstr = "&TOKEN=".$token;
		$resArray = self::makeCall("GetExpressCheckoutDetails",$nvpstr);
		$log = fopen('paypal.txt', 'a+');
		fwrite($log, "【GetExpressCheckoutDetails\t".$token."】\t".date('Y-m-d H:i:s')."\n".json_encode($resArray)."\n\n");
		fclose($log);
		if(!$resArray) {
			return false;
		}
		if(array_key_exists('ACK', $resArray) AND strtoupper($resArray['ACK']) == 'SUCCESS') {
			return $resArray;
		} else {
			return false;
		}
	}

	//确定执行交易
	public function DoExpressCheckoutPayment($params) {//token,payAmount,payType,PayerID
		$this->API_UserName		= $params['API_UserName'];
		$this->API_Password		= $params['API_Password'];
		$this->API_Signature	= $params['API_Signature'];

		$token		= urlencode( $params['token']);
		$payAmount	= urlencode ($params['amount']);
		$payType	= urlencode(isset($params['payType'])?$params['payType']:'sale');
		$payerID	= urlencode($params['PayerID']);
		$nvpstr = '&TOKEN='.$token.'&PAYERID='.$payerID.'&PAYMENTACTION='.$payType.'&AMT='.$payAmount."&INVNUM=".$params["INVNUM"];

		$resArray = self::makeCall("DoExpressCheckoutPayment",$nvpstr);
		$log = fopen('paypal.txt', 'a+');
		fwrite($log, "【DoExpressCheckoutPayment\t".$params["INVNUM"]."】\t".date('Y-m-d H:i:s')."\n".json_encode($resArray)."\n\n");
		fclose($log);

		if(!$resArray) {
			return false;
		}
		if(array_key_exists('ACK', $resArray) AND strtoupper($resArray['ACK']) == 'SUCCESS') {
			return $resArray;
		} else {
			return false;
		}
	}

	//通过curl库来发送请求，被以上的函数调用
	private function makeCall($methodName,$nvpStr) {
		$nvpreq	= "METHOD=".urlencode($methodName)."&VERSION=".urlencode($this->version)."&PWD=".urlencode($this->API_Password)."&USER=".urlencode($this->API_UserName)."&SIGNATURE=".urlencode($this->API_Signature).$nvpStr;
		$ch		= curl_init();
		curl_setopt($ch, CURLOPT_URL,$this->API_ENDPOINT);
		curl_setopt($ch, CURLOPT_VERBOSE, 1);
		curl_setopt($ch, CURLOPT_SSLVERSION, 6);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $nvpreq);
		$response	= curl_exec($ch);
		$error		= curl_error($ch);
		curl_close($ch);
		// var_dump($error);
		$nvpResArray	= self::deformatNVP($response);
		if (!$response) {
			return false;
		}
		return $nvpResArray;
	}
	/*其实就是把字符串转为了数组--By YH*/
	private function deformatNVP($nvpstr) {
		$nvpstr = explode('&', $nvpstr);
		$nvpArray = [];
		foreach ($nvpstr as $key => $value) {
			$arr = [];
			$arr = explode('=', $value);
			$nvpArray[urldecode($arr[0])] = urldecode($arr[1]);
		}
		return $nvpArray;
	}
}
